package com.mediacloud.app.newsmodule.fragment.baoliao;


import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.yoake.media.player.XPlayer;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoItem;

import org.json.JSONArray;
import org.json.JSONObject;


/**
 *
 */
public class XPlayerVideoListPlayerUtil {

    private Context context;
   private volatile XPlayer mPlayer;
   // private Object mark = System.currentTimeMillis();
    private View listView;
    private RelativeLayout container;
    private View rootView;
    public View mengban;


    public XPlayerVideoListPlayerUtil(Context context, View listView) {
        this.context = context;
        this.listView = listView;
        initPlayer();
      //  setVideoPlayerListener();
        setListViewOnScrollListener();
    }

    private void initPlayer() {
       XPlayer tmp = new XPlayer(context);
        mPlayer = tmp;
        mPlayer.setAutoPlay(true);
     //   mPlayer.hideTitleMore();
        mPlayer.hideTitleLayoutWhenInNormalState();
    }


    /**
     * 设置播放器的容器
     *
     * @param container 播放器的容器
     */
    public void setPlayerContainer(View rootView, RelativeLayout container, View view) {
        if (this.mengban != null && this.mengban != view) this.mengban.setVisibility(View.VISIBLE);
        this.mengban = view;
        if (mPlayer == null)
            return;
        mPlayer.release();
        this.container = container;

        this.rootView = rootView;
        if (mPlayer.getParent() != null) {
            RelativeLayout rl = (RelativeLayout) mPlayer.getParent();
            rl.removeView(mPlayer);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

        this.container.addView(mPlayer, params);
    }

    /**
     * 释放资源，移除父布局
     */
    public void stopPlay() {
        if (mPlayer != null && mPlayer.getParent() != null) {
            ViewGroup rl = (ViewGroup) mPlayer.getParent();
            if (mPlayer != null) {
                if (mPlayer.isPlaying()){
                    mPlayer.pause();
                }
                mPlayer.release();
            }
            rl.removeView(mPlayer);
        }
    }


    int mScrollState;
    /**
     * 监听ListView 滚动
     */
    private void setListViewOnScrollListener() {
        if(listView==null)
            return;
        if(listView instanceof RecyclerView)
        {
            ((RecyclerView)listView).addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    mScrollState = newState;
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    onScrolledHandle();
                }
            });
        }
        else if(listView instanceof ScrollView)
        {
            listView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                    onScrolledHandle();
                }
            });
        }
        else if(listView instanceof NestedScrollView) {
            ((NestedScrollView) listView).setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener()
            {

                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY)
                {
                    onScrolledHandle();
                }
            });
        }
        else if(listView instanceof ListView)
        {
            ((ListView) listView).setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {


                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    onScrolledHandle();
                }
            });
        }
    }
    Rect rect=new Rect();
    private void onScrolledHandle()
    {
        if(rootView==null||listView==null)
            return;
        rect.set(rootView.getLeft(), rootView.getTop(), listView.getMeasuredWidth(), listView.getMeasuredHeight());
        if(!container.isShown()||!container.getLocalVisibleRect(rect))
        {
            stopPlay();
        }
    }


    public void setVideoData(JSONObject video) {

        if (video != null) {

            mPlayer.release();
            try {

                String poster = video.optString("poster", "");
                mPlayer.setPoster(ImageKitKt.buildUrl(3,poster), ContextCompat.getDrawable(context, R.drawable.cctv7_loading_img));
                JSONArray tsAddress = VideoAddressGet.getAddress(video);
                XVideoItem videoPlayObj = new XVideoItem("");
                String cdnEncypt = video.optString("cdnConfigEncrypt");
                videoPlayObj.setCdnIv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                videoPlayObj.setCdnKey(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);

                for (int i = 0; i < tsAddress.length(); i++) {
                    JSONObject line = tsAddress.optJSONObject(i);
                    XVideoBitRate lineItem = new XVideoBitRate();
                    lineItem.setPath(line.optString("url"));
                    lineItem.setTitle(line.optString("title"));
                    lineItem.setCdnEncypt(cdnEncypt);
                    videoPlayObj.getBitRates().add(lineItem);
                }
                mPlayer.addVideoItemReverse(videoPlayObj,"源码",true);
            } catch (Exception e) {
                e.printStackTrace();
                mPlayer.onExternalError();
            }
        } else {
            mPlayer.onExternalError();
        }
    }

//    /**
//     * 设置播放器各种监听
//     */
//    private void setVideoPlayerListener() {
//
//        mPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
//
//            @Override
//            public void onResume(int currentMediaIndex) {
//                super.onResume(currentMediaIndex);
//                if (playListener!= null)
//                    playListener.setPlay(true);
//            }
//
//            @Override
//            public void onpause(int currentMediaIndex) {
//                super.onpause(currentMediaIndex);
//                if (playListener!= null)
//                    playListener.setPlay(false);
//            }
//
//            @Override
//            public void oncomplete(int currentMediaIndex) {
//                super.oncomplete(currentMediaIndex);
//                if (mPlayer.isFullScreen()) {
//                    mPlayer.toggleFullScreen();
//                }
//                mPlayer.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        stopPlay();
//                    }
//                }, 800);
//            }
//
//            @Override
//            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
//                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
//                if (isFullScreen) {
//                    FrameLayout rootView = (FrameLayout) ((Activity) context).getWindow().getDecorView();
//                    ViewGroup parent = (ViewGroup) mPlayer.getParent();
//                    FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
//                    parent.removeView(mPlayer);
//                    rootView.addView(mPlayer, frameLayoutParams);
//                } else {
//                    if (mPlayer != null && mPlayer.getParent() != null) {
//                        ViewGroup parent = (ViewGroup) mPlayer.getParent();
//                        parent.removeView(mPlayer);
//                    }
//                    if (mPlayer != null) {
//                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
//                        container.addView(mPlayer, params);
//                    }
//                }
//            }
//
//            @Override
//            public void onPrepared(int currentMediaIndex) {
//                super.onPrepared(currentMediaIndex);
//                mPlayer.toggleFullScreenEnable(true);
//                if (playListener!= null)
//                 playListener.setPlay(true);
//            }
//        });
//
//    }
//
    public void onDestroy() {
        if (mPlayer != null) {
            if (context instanceof LifecycleOwner) {
                ((LifecycleOwner) context).getLifecycle().removeObserver(mPlayer);
            }
            mPlayer.getConnectivityEngine().unregisterNetworkChangeListener();
            if (mPlayer.getAdImageView() != null) {
                mPlayer.getAdImageView().cancelCountDown();
            }
            if (mPlayer.getCdnUrl() != null) {
                mPlayer.getPreloadManager().removePreloadTask(mPlayer.getCdnUrl());
            }
            if (mPlayer.getVRLibrary() != null) {
                mPlayer.getVRLibrary().onDestroy();
            }
            if (mPlayer.getParent() != null) {
                ((ViewGroup) mPlayer.getParent()).removeView(mPlayer);
            }
            mPlayer.release();
        }


        context = null;
    }

    public XPlayer getPlayer() {
        return mPlayer;
    }

    public void setVideoData(String poster,String video) {
        if (video != null) {

            mPlayer.release();
            try {

                mPlayer.setPoster(ImageKitKt.buildUrl(3,poster),ContextCompat.getDrawable(context,R.drawable.cctv7_loading_img));
                mPlayer.showLoadingAnimation();
                XVideoItem videoPlayObj = new XVideoItem("");
                XVideoBitRate lineItem = new XVideoBitRate();
                lineItem.setPath(video);
                lineItem.setTitle("标清");
                videoPlayObj.getBitRates().add(lineItem);
                mPlayer.addVideoItem(videoPlayObj,true);
            } catch (Exception e) {
                e.printStackTrace();
                mPlayer.onExternalError();
            }
        } else {
            mPlayer.onExternalError();
        }
    }

    public interface playCallBack{
        void setPlay(boolean play);
    }
    private playCallBack playListener;
    public void setPlayCallBack(playCallBack callBack){
        playListener = callBack;
    }


}